package com.cn.utlis;

import javax.persistence.Table;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author: chenyuncong
 * @Date: 2020/4/15 9:56
 */
public class CreateSqlUtils {
    public static String getInsertSQL(Object f) throws Exception {
        String name;
        StringBuffer sb = new StringBuffer("insert into ");
        Table table = f.getClass().getAnnotation(Table.class);
        String tableName = table.name();
        sb.append(tableName).append("(");

        for (Field field : f.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            name = field.getName();
            if (!name.equals("id")) {
                sb.append(name).append(",");
            }
        }
        if(sb.length()>0){
            sb.deleteCharAt(sb.length()-1);
        }
        sb.append(") values ");
        return sb.toString();
    }

    public static void setSQLValues(Object f,StringBuffer sb) throws Exception {
        sb.append("(");
        String fieldName=null;
        String methodName=null;
        Method method=null;
        Object resultValue=null;
        for (Field field : f.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            fieldName = field.getName();
            if(fieldName.equals("id")){
                continue;
            }
            methodName = "get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
            method = f.getClass().getMethod(methodName, new Class[]{});
            resultValue = method.invoke(f, new Object[]{});
            if (resultValue instanceof Integer){
                sb.append(resultValue).append(",");
            }else if(resultValue instanceof String){
                if(resultValue.equals("'")){
                    sb.append("'").append(((String) resultValue).replaceAll("'","")).append("',");
                }else{
                    sb.append("'").append(resultValue).append("',");
                }
            }else{
                sb.append("NULL").append(",");
            }
        }
        if(sb.length()>0){
            sb.deleteCharAt(sb.length()-1);
        }
        sb.append(")");
    }
}
